package postgres

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	logger "pay/collector/logger"
	"pay/config"
	"pay/errors"
	"pay/model"
	"pay/model/entity"
	"pay/utils"
)

var FeePlanGroup = &feePlanGroup{}

type feePlanGroup struct{}

func init() {
	Register(FeePlanGroup)
}

func (a *feePlanGroup) Init() {
	if config.Conf.AutoMigrate {
		p := &entity.FeePlanGroup{}
		if db.Migrator().HasTable(p) {
			logger.Debug("table already exist: ", zap.String("table", p.TableName()))
			return
		}
		if err := db.AutoMigrate(p); err != nil {
			logger.Error("filed to create table please check config or manually create", zap.String("table", p.TableName()), zap.String("err", err.Error()))
		} else {
			logger.Info("create table successfully", zap.String("table", p.TableName()))
		}
	}
}

// Create
func (a *feePlanGroup) Create(ctx context.Context, m *entity.FeePlanGroup) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find detail
func (a *feePlanGroup) Find(ctx context.Context, in *model.FeePlanGroupInfoRequest) (*entity.FeePlanGroup, error) {
	e := &entity.FeePlanGroup{}

	q := GetDB(ctx).Model(&entity.FeePlanGroup{})

	if in.Id == 0 {
		return e, errors.New("condition illegal")
	}
	err := q.First(&e, in.Id).Error
	return e, err
}

// Update
func (a *feePlanGroup) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.FeePlanGroup{}).Where("id = ?", id).Updates(dict).Error
}

// Delete
func (a *feePlanGroup) Delete(ctx context.Context, id int64) error {
	return GetDB(ctx).Delete(&entity.FeePlanGroup{}, id).Error
}

// List query list
func (a *feePlanGroup) List(ctx context.Context, in *model.FeePlanGroupListRequest, opts ...model.QueryOptions) (int, []*entity.FeePlanGroup, error) {

	var (
		opt           = model.GetQueryOption(opts...)
		q             = GetDB(ctx).Model(&entity.FeePlanGroup{})
		err           error
		total         int64
		feePlanGroups []*entity.FeePlanGroup
	)

	if in.Id != nil {

		q = q.Where("id = ?", in.Id)

	}

	if in.Name != nil {

		q = q.Where("name like ?", utils.SqlLike(in.Name))

	}

	if in.Remark != nil {

		q = q.Where("remark like ?", utils.SqlLike(in.Remark))

	}

	if in.FeePlanId != nil {

		q = q.Where("? = ANY(fee_plan_ids)", *in.FeePlanId)

	}

	if in.FeePlanIds != nil {

		q = q.Where("fee_plan_ids && ARRAY[?]::bigint[]", in.FeePlanIds)

	}

	if in.Def != nil {

		q = q.Where("def = ?", in.Def)

	}

	if in.Enable != nil {

		q = q.Where("enable = ?", in.Enable)

	}

	if in.CreatedAt != nil {

		q = q.Where("created_at = ?", in.CreatedAt)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}
	if len(opt.SelectFields) > 0 {
		q = q.Select(opt.SelectFields)
	}

	if len(opt.OrderFields) > 0 {
		q = q.Order(fmt.Sprintf("%v", model.ParseOrder(opt.OrderFields)))
	}

	b := !opt.OnlyCount && !opt.OnlyList
	if opt.OnlyCount || b {
		if err = q.Count(&total).Error; err != nil {
			return 0, nil, err
		}
	}

	if opt.OnlyList || b {
		if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&feePlanGroups).Error; err != nil {
			return 0, nil, err
		}
	}
	return int(total), feePlanGroups, nil
}

// ExecTransaction execute database transaction
func (a *feePlanGroup) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, ContextTxKey, tx)
		return callback(ctx)
	})
}
